<?php
/**
 * Application level Controller
 *
 * This file is application-wide controller file. You can put all
 * application-wide controller-related methods here.
 *
 * PHP 5
 *
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link          http://cakephp.org CakePHP(tm) Project
 * @package       app.Controller
 * @since         CakePHP(tm) v 0.2.9
 * @license       MIT License (http://www.opensource.org/licenses/mit-license.php)
 */

App::uses('Controller', 'Controller');

/**
 * Application Controller
 *
 * Add your application-wide methods in the class below, your controllers
 * will inherit them.
 *
 * @package       app.Controller
 * @link http://book.cakephp.org/2.0/en/controllers.html#the-app-controller
 */
class AppController extends Controller {
	public $ext = '.php';

    public function beforeFilter() {
        parent::beforeFilter();

        //set user
        $this->loadModel("User");
        if(isset($_SESSION['user_id'])) if($_SESSION['user_id']){

            $login = $this->User->findById($_SESSION['user_id']);
            if($login){
                $this->user_login = $login['User'];
                $this->set('user_login',$login['User']);
                $this->User->id=$_SESSION['user_id'];
                $this->User->saveField('activity', time());
                
                //load mess
                $this->loadModel("Tinnhan");
                $list_mess = $this->Tinnhan->find('all', array(
                    'conditions' => array(
                        'Tinnhan.status' => 0,
                        'Tinnhan.user_id' => $login['User']['id'],
                    ),
                    'order' => 'Tinnhan.id DESC'
                ));
                $this->set('list_mess', $list_mess);
                
                //load thongbao
                $this->loadModel("Thongbao");
                date_default_timezone_set('Asia/Ho_Chi_Minh');
                $list_thongbao = $this->Thongbao->find('all', array(
                    'conditions' => array(
                        'Thongbao.status' => 0,
                        'Thongbao.created >=' => date('Y-m-d H:i:s', time()-8400*2),
                        'Thongbao.user_id' => $login['User']['id'],
                    ),
                    'order' => 'Thongbao.id DESC'
                ));
                $this->set('list_thongbao', $list_thongbao);
            }
        }
        
        
        

        //session ngon ngu
        /*if(isset($_GET['lang'])) {
            if($_GET['lang']=="vie") {
                 $this->Session->write('lang',"");
            }
            elseif($_GET['lang']=="eng") {
                 $this->Session->write('lang','_eng');
            }
            $this->redirect($this->referer());
        }else{
            if($this->Session->check('lang')){
                $this->Session->write('lang',$this->Session->read('lang'));
            }
            else{
                $this->Session->write('lang',"");
            }
        }*/

        //set menu
        //$app_menu = $this->multiMenu(1, null);
        //$this->set('app_menu', $app_menu);

        //set menu doc
        $app_menu_doc = $this->menudoc(6, null);
        $this->set('app_menu_doc', $app_menu_doc);
        
        $app_menu_doc_event = $this->menudoc_event(13, null);
        $this->set('app_menu_doc_event', $app_menu_doc_event);
    
    

        //set menu footer
        $app_menu_footer = $this->menufooter(null, null);
        $this->set('app_menu_footer', $app_menu_footer);

        //load qu?ng cáo
        $this->loadModel('Extention');
        $quangcao = $this->Extention->find('all', array(
            'conditions' => array(
                'Extention.status' => 1,
                'Extention.type' => 'advertisement'
            )
        ));
        $this->set('quangcao', $quangcao);

        $quangcaotrai = $this->Extention->find('all', array(
            'conditions' => array(
                'Extention.status' => 1,
                'Extention.type' => 'adv'
            )
        ));
        $this->set('quangcaotrai', $quangcaotrai);
        
        //set logo
        $banner = $this->Extention->find('first', array(
            'conditions' => array(
                'Extention.status' => 1,
                'Extention.type' => 'banner'
            )
        ));
        $this->set('banner', $banner);
        //set bn center
        $bannercenter = $this->Extention->find('first', array(
            'conditions' => array(
                'Extention.status' => 1,
                'Extention.type' => 'bannercenter'
            )
        ));
        $this->set('bannercenter', $bannercenter);
        //set bn right
        $bannerright = $this->Extention->find('first', array(
            'conditions' => array(
                'Extention.status' => 1,
                'Extention.type' => 'bannerright'
            )
        ));
        $this->set('bannerright', $bannerright);

        $this->loadModel('Catproduct');
        $titledanhmucbaiviet = $this->Catproduct->find('first', array(
            'fields' => array('id', 'name', 'name_eng', 'link'),
            'conditions' => array(
                'Catproduct.id' => 6
            )
        ));
        $this->set('titledanhmucbaiviet', $titledanhmucbaiviet);

        $list_cat = $this->Catproduct->treelist(
            array(
                'conditions' => array(
                    'Catproduct.parent_id <>' => null,
                    'Catproduct.type'=>'new'
                ),
                'order' => array('Catproduct.order'=>'ASC', 'Catproduct.id'=>'ASC'),
            ),
            ' -- '
        );
        $this->set('list_cat', $list_cat);
        
        $list_sukien_baiviet = $this->Catalogue->treelist(
            array(
                'conditions' => array(
                    'Catalogue.parent_id' => null,
                    'Catalogue.type' => 'new'
                ),
                'order' => 'Catalogue.id ASC',
            ),
            ' -- '
        );
        $this->set('list_sukien_baiviet', $list_sukien_baiviet);

        $ytuong = $this->Catproduct->treelist(
            array(
                'conditions' => array(
                    'Catproduct.parent_id <>' => null,
                    'Catproduct.type'=>'ytuong'
                ),
                'order' => array('Catproduct.order'=>'ASC', 'Catproduct.id'=>'ASC'),
            ),
            ' -- '
        );
        $this->set('ytuong', $ytuong);
        
        
        $parmenuProduct = $this->Catproduct->find('all', array(
            'conditions' => array(
                'Catproduct.id' => array('8', '7')
            ),
            'order' => 'Catproduct.order ASC'
        ));
        $listdanhmuc = array();
        foreach($parmenuProduct as $values){
            $list = $this->Catproduct->find('all', array(
                'conditions' => array(
                    'Catproduct.parent_id' => $values['Catproduct']['id'],
                    'Catproduct.status' => 1
                ),
                'order' => 'Catproduct.order ASC'
            ));
            //gop ten cha + noi dung
            $listdanhmuc[] = array(
                'id' => $values['Catproduct']['id'],
                'name' => $values['Catproduct']['name'],
                'list' => $list
            );
        }
        $this->set('listdanhmuc', $listdanhmuc);

        //set gia tri setting website
        $this->loadModel('Setting');
        $setting = $this->Setting->find('first');
        if(!empty($setting)){
            $this->Main_Setting = $setting['Setting'];
            $this->set('setting', $setting['Setting']);
            $this->set('title_for_layout', $setting['Setting']['title']);
            $this->set('keywords_for_layout', $setting['Setting']['meta_key']);
            $this->set('description_for_layout', $setting['Setting']['meta_des']);
        }

        //set title cac trang
        $titleDefinitions = array(
            'baiviet' => 'Bài viết',
            'cacbaikhac' => 'Các bài khác',
            'tinlienquan' => 'Các bài liên quan',
            'vietbinhluan' => 'Viết bình luận',
        );
        $this->set('titleDefinitions', $titleDefinitions);
    }

    public $notice = array(
        'not_exits_link'   =>  'Không tồn tại bài viết !',
        'not_exits'   =>  'Không tồn tại !',
        'add_success'   =>  'Thành công !',
        'add_fail'   =>  'Lỗi xẩy ra !',
        'ck_login'   =>  'Bạn phải đăng nhập để sử dụng chức năng này !',
        'friend_success'   =>  'Kết bạn thành công !',
        'friend_err'   =>  'Kết bạn không thành công !',
        'friend_double'   =>  'Bạn không thể kết bạn với chính mình !',
        'friend_exits'   =>  'Bạn với người này đã là bạn của nhau !',
        'friend_delete_double'   =>  'Không thể hủy kết bạn với chính mình !',
        'friend_delete_not_extis'   =>  'Bạn và người này chưa là bạn của nhau !',
        'friend_delete'   =>  'Hủy kết bạn thành công !',
        'friend_delete_err'   =>  'Hủy kết bạn không thành công !',
        
        'follow_success'   =>  'Theo dõi thành công !',
        'follow_err'   =>  'Theo dõi không thành công !',
        'follow_double'   =>  'Bạn không thể theo dõi với chính mình !',
        'follow_exits'   =>  'Bạn đã theo dõi người này !',
        'follow_delete_double'   =>  'Không thể hủy theo dõi với chính mình !',
        'follow_delete_not_extis'   =>  'Bạn và người này chưa theo dõi nhau !',
        'follow_delete'   =>  'Hủy theo dõi thành công !',
        'follow_delete_err'   =>  'Hủy theo dõi không thành công !',
        'ck_acc' => 'Bạn đang sửa thông tin không phải là của mình !',
    );


    public function multiMenu($parentid = null, $trees = NULL) {
        $this->loadModel('Catproduct');
        $parmenu = $this->Catproduct->find('all', array(
            'fields' => array('id', 'name', 'name_eng', 'link'),
            'conditions' => array(
                'Catproduct.parent_id' => $parentid,
                'Catproduct.status' => 1,
            ),
            'order' => 'Catproduct.order ASC'
            ));
        if (count($parmenu) > 0) {
            $trees .='<ul>';
            foreach ($parmenu as $field) {
                if($parentid != null){
                    $trees .= '<li><a href="' . DOMAIN . $field['Catproduct']['link'] .  '">' . $field['Catproduct']['name'.$this->Session->read('lang')] . '</a>';
                    $trees = $this->multiMenu($field['Catproduct']['id'], $trees);
                    $trees .='</li>';
                }else{
                    $test_menu = $this->Catproduct->find('first', array(
                        'fields' => array('id', 'name', 'link'),
                        'conditions' => array(
                            'Catproduct.parent_id' => $field['Catproduct']['id'],
                            'Catproduct.status' => 1,
                        ),
                        'order' => 'Catproduct.order ASC'
                    ));
                    $muiten = '';
                    if($test_menu) $muiten = '<i class="fa fa-caret-down" style="margin-left: 10px;"></i>';
                    $trees .= '<li><a href="' . DOMAIN . $field['Catproduct']['link'] . '">' . $field['Catproduct']['name'.$this->Session->read('lang')] . $muiten . '</a>';
                    $trees = $this->multiMenu($field['Catproduct']['id'], $trees);
                    $trees .='</li>';
                }
            }
            $trees .='</ul>';
        }
        return $trees;
    }
    
    public function ckacc($var = null){
        if($var != $_SESSION['user_id']){
            if(isset($this->notice['ck_acc'])) $this->Session->setFlash($this->notice['ck_acc'], 'default', array('class' => 'alert alert-error'));
            $this->redirect(Router::url(array('controller' => 'User', 'action' => 'login'), true));
            exit;
        }
    }

    public function cklogin(){

        if(empty($_SESSION['user_id'])){
            if(isset($this->notice['ck_login'])) $this->Session->setFlash($this->notice['ck_login'], 'default', array('class' => 'alert alert-error'));
            $this->redirect(Router::url(array('controller' => 'User', 'action' => 'login'), true));
            exit;
        }else{
            $login = $this->User->findById($_SESSION['user_id']);
            if(empty($login)){
                if(isset($this->notice['ck_login'])) $this->Session->setFlash($this->notice['ck_login'], 'default', array('class' => 'alert alert-error'));
                $this->redirect(Router::url(array('controller' => 'User', 'action' => 'login'), true));
                exit;
            }
        }
        return true;
    }

    public function checklogin(){
        if(!isset($_SESSION['user_id'])){
            $this->Session->write('back_after_login',DOMAIN.$this->request->url);
            $this->redirect(DOMAIN.'user/login');
        }
        $this->loadModel('User');
        $login = $this->User->findById($_SESSION['user_id']);
        if(!$login){
            $this->Session->setFlash('Vui lòng đăng nhập!', 'default', array('class' => 'alert alert-error'));
            $this->Session->write('back_after_login',DOMAIN.$this->request->url);
            $this->redirect(DOMAIN.'user/login');
        }
        return true;
    }

    public function menudoc($parentid = null, $trees = NULL) {
        $this->loadModel('Catproduct');
        $parmenu = $this->Catproduct->find('all', array(
            'fields' => array('id', 'name', 'name_eng', 'link', 'images'),
            'conditions' => array(
                'Catproduct.parent_id' => $parentid,
                'Catproduct.status' => 1
            ),
            'order' => 'Catproduct.order ASC'
            ));
        if (count($parmenu) > 0) {
            $trees .='<ul>';
            foreach ($parmenu as $field) {
                if($parentid != null){
                    $img = null;
                    if($field['Catproduct']['images']){
                        $img = "style='background: #efefef url(".DOMAIN."img/h15/".$field['Catproduct']['images'].") no-repeat top 8px left 6px;'";
                    }
                    $menu_child = $this->Catproduct->findByParent_id($field['Catproduct']['id']);
                    $mt = null;
                    if(!empty($menu_child)) $mt = '<i class="fa fa-caret-right"></i>';
                    
                    $trees .= '<li '.$img.'>'.$mt.'<a href="' . DOMAIN . $field['Catproduct']['link'] .  '">' . $field['Catproduct']['name'.$this->Session->read('lang')] . '</a>';
                    $trees = $this->menudoc($field['Catproduct']['id'], $trees);
                    $trees .='</li>';
                }else{
                        
                        $trees .= '<li><a href="' . DOMAIN . $field['Catproduct']['link'] . '">' . $field['Catproduct']['name'.$this->Session->read('lang')] . '</a>';
                        $trees = $this->menudoc($field['Catproduct']['id'], $trees);
                        $trees .='</li>';
                    }
            }
            $trees .='</ul>';
        }
        return $trees;
    }
    
    public function menudoc_event($parentid = null, $trees = NULL) {
        $this->loadModel('Catalogue');
        $parmenu = $this->Catalogue->find('all', array(
            'fields' => array('id', 'name', 'name_eng', 'link', 'images'),
            'conditions' => array(
                'Catalogue.parent_id' => $parentid,
                'Catalogue.status' => 1
            ),
            'order' => 'Catalogue.order ASC'
            ));
        if (count($parmenu) > 0) {
            $trees .='<ul>';
            foreach ($parmenu as $field) {
                if($parentid != null){
                    $img = null;
                    if($field['Catalogue']['images']){
                        $img = "style='background: #efefef url(".DOMAIN."img/h15/".$field['Catalogue']['images'].") no-repeat top 8px left 6px;'";
                    }
                    $menu_child = $this->Catalogue->findByParent_id($field['Catalogue']['id']);
                    $mt = null;
                    if(!empty($menu_child)) $mt = '<i class="fa fa-caret-right"></i>';
                    
                    $trees .= '<li '.$img.'>'.$mt.'<a href="' . DOMAIN .'bai-viet/'. $field['Catalogue']['link'] .  '">' . $field['Catalogue']['name'.$this->Session->read('lang')] . '</a>';
                    $trees = $this->menudoc_event($field['Catalogue']['id'], $trees);
                    $trees .='</li>';
                }else{
                        
                        $trees .= '<li><a href="' . DOMAIN .'bai-viet/'. $field['Catalogue']['link'] . '">' . $field['Catalogue']['name'.$this->Session->read('lang')] . '</a>';
                        $trees = $this->menudoc_event($field['Catalogue']['id'], $trees);
                        $trees .='</li>';
                    }
            }
            $trees .='</ul>';
        }
        return $trees;
    }

    public function menufooter($parentid = null, $trees = NULL) {
        $this->loadModel('Catalogue');
        $parmenu = $this->Catalogue->find('all', array(
            'fields' => array('id', 'name', 'name_eng', 'link', 'url'),
            'conditions' => array(
                'Catalogue.parent_id' => $parentid,
                'Catalogue.status' => 1,
                'Catalogue.type' => 'product'
            ),
            'order' => 'Catalogue.order ASC'
            ));
        if (count($parmenu) > 0) {
            $trees .='<ul>';
            foreach ($parmenu as $field) {
                if($parentid != null){
                    $trees .= '<li><a href="' . DOMAIN .'bai-viet/'. $field['Catalogue']['link']. '">' . $field['Catalogue']['name'.$this->Session->read('lang')] . '</a>';
                    $trees = $this->menufooter($field['Catalogue']['id'], $trees);
                    $trees .='</li>';
                }else{
                        $trees .= '<li><a href="' . DOMAIN .'bai-viet/'. $field['Catalogue']['link']. '">' . $field['Catalogue']['name'.$this->Session->read('lang')] . '</a>';
                        $trees = $this->menufooter($field['Catalogue']['id'], $trees);
                        $trees .='</li>';
                    }
            }
            $trees .='</ul>';
        }
        return $trees;
    }


    public function multiMenuProduct($parentid = null, $trees = NULL) {
        $this->loadModel('Catproduct');
        $parmenu = $this->Catproduct->find('all', array(
            'conditions' => array(
                'Catproduct.parent_id' => $parentid,
                'Catproduct.status' => 1
            ),
            'order' => 'Catproduct.order ASC'
            ));
        if (count($parmenu) > 0) {
            foreach ($parmenu as $field) {
                $trees[$field['Catproduct']['id']] = $field['Catproduct']['id'];
                $trees = $this->multiMenuProduct($field['Catproduct']['id'], $trees);
            }
        }
        return $trees;
    }

}